<?php
namespace app\erp_meixingtiyu\model;

use think\Model;
use app\common\model\UploadFile;

class Course extends Model
{
    protected $table = 'athlon_course';
    protected $pk = 'course_id';

    public function image()
    {
        return $this->hasOne(UploadFile::class, 'file_id', 'image_id');
    }

    public function coachs()
    {
        return $this->belongsToMany(
            Coach::class,
            CourseCoach::class,
            'employee_id',
            'course_id'
        );
    }

    public function lessons()
    {
        return $this->hasMany(CourseLesson::class);
    }

    public function getListByPaginate()
    {
        return $this->with(['image', 'coachs'])
            ->order('sort asc')
            ->paginate(15);
    }

    public function createCourse($data)
    {
        $this->transaction(function () use ($data) {
            $course = self::create($data);
            $course->coachs()->attach($data['employee_ids']);
        });
    }

    public function updateCourse($data)
    {
        $this->transaction(function () use ($data) {
            $course = self::update($data);
            $course->coachs()->detach($course->coachs);
            $course->coachs()->attach($data['employee_ids']);
        });
    }

    public function destoryCourse($courseId)
    {
        return self::destroy($courseId);
    }

}
